<template>
  <div class="order">
    <van-sticky>
      <div class="order-search">
        <van-icon class="arrow-left" name="arrow-left" @click="$router.push({name:'my'})" />
        <van-search v-model="searchValue" placeholder="请输入搜索关键词" @input="onSearch" @clear="searchValue = ''" />
      </div>

      <van-tabs v-model="tabs_active" @change="tabChange" swipeable scrollspy>
        <van-tab v-for="(column,index) in tab_column" :title="column" :name="index" :key="index">
        </van-tab>
      </van-tabs>
    </van-sticky>

    <van-list v-model="loading" :finished="finished" :finished-text="!loading?'没有更多了~':''" :error.sync="err" error-text="加载失败，点击这里重试" @load="getOrderList">
      <div class="list" v-for="(item, index) in list" :key="index">
        <van-cell-group inset class="order-list-panel" :border="false">
          <div @click="selectOrderDetail(item.order_id)">
            <van-cell class="shopname" :title="item.shop_name" :value-class="item.order_status==1?'red-special':''" :border="false" center>
              <template #icon>
                <van-image :src="item.imagesurl==''?require('@/assets/img/shopicon.png'):`${resourceURL}${item.imagesurl}`" />
              </template>
              <template #default>
                <div>{{status[item.order_status]}}</div>
              </template>
            </van-cell>
            <!-- order_type: 1,  1购买普通商品 2兑换商品 -->
            <van-card v-for="(items, index) in item.children" :key="index" :title="items.product_name" :num="items.quantity" :thumb="`${resourceURL}${items.cover_url}`" :desc="items.p_s_name">
              <template #price>
                <div v-if="item.order_type==1">￥{{items.sale_price}}</div>
                <div v-if="item.order_type==2">{{items.growth_coin}} 积分</div>
              </template>
            </van-card>
            <van-cell class="pay_amount" title="" :border="false">
              <template #default>
                <span class="express_fee">{{item.express_fee>0?'含运费':''}}</span>
                <span class="name">{{item.order_status==6?'退款成功':'实付款'}} <span class="price">
                    ￥{{item.order_type==1?item.pay_amount:item.express_fee}}
                  </span> </span>
              </template>
            </van-cell>
          </div>
          <div class="list-item-options">
            <van-button size="small" v-if="item.order_status==4" class="btn" round @click=onAddCartClicked(item.children)> 再次购买</van-button>
            <van-button size="small" v-if="item.order_status==1"  type="default" round plain @click="cancelOrder(item.order_id)">取消订单</van-button>
            <van-button v-if="item.order_status==2 &&  item.is_prize!=2" size="small" class="btn " type="primary" round plain @click="remindSend(item.order_id)">提醒发货</van-button>
            <van-button v-if="item.order_status==3" size="small" type="default" round plain @click="logistics(item.order_id)">查看物流</van-button>
            <!-- <van-button v-if="item.order_type==1 && item.order_status==4" size="small" type="default" round plain @click="refund(item)">退款</van-button> -->
            <van-button v-if="item.order_status==1" size="small" type="primary" class="changebu" round @click="changeOrderState(1,item.order_id)">支付</van-button>
            <van-button v-if="item.order_status==3" size="small" type="primary" class="btn" round @click="changeOrderState(2,item.order_id)" plain>确认收货</van-button>
            <van-button v-if="item.order_status==4&&item.is_comment==0&&item.order_type==1" size="small" type="primary" class="btn" round plain @click="jumpToComment(item.order_id)">评价</van-button>
            <!-- <van-button v-if="item.order_status==10||item.order_status==7||item.order_status==6" size="small" @click="goCustomerService(item)" round>联系客服</van-button> -->
            <van-button v-if="item.order_status==10" size="small" class="btn" round @click="userafters(item.order_id)"> 撤回申请</van-button>

          </div>
        </van-cell-group>
      </div>
      <van-empty v-if="list.length==0 && !loading" />
    </van-list>

    <van-dialog v-model="show" title="取消原因" show-cancel-button @confirm="onConfirm">
      <van-field v-model="reson" rows="3" autosize type="textarea" maxlength="200" placeholder="请输入取消订单原因" show-word-limit />
    </van-dialog>

  </div>
</template>

<script>
import { Dialog, Toast } from "vant";
export default {
  data () {
    return {
      searchValue: "",
      tabs_active: 0,
      tab_column: {
        0: "全部",
        1: "待付款",
        2: "待发货",
        3: "待收货",
        4: "待评价",
        5: "售后",
      }, // tab选项卡标题
      status: {
        1: "待付款",
        2: "待发货",
        3: "待收货",
        4: "已完成",
        5: "已取消",
        6: "订单退款",
        7: "订单退货",
        10: '提交售后'
      }, // 订单状态
      order_type: { 1: "购买", 2: "兑换" }, //订单类型 1购买普通商品 2兑换商品
      show: false,
      err: false,
      loading: false,
      finished: false,
      list: [],
      page: 1,
      limit: 6,
      reson: "",
      oid: "",
      temp_id: "",
    };
  },
  created () {
    this.tabs_active = this.$store.state.orderTab;
    this.getOrderList();
  },
  methods: {
    // 再次购买
    onAddCartClicked (list) {

      let arr = []
      list.forEach(ele => {
        this.$axios.post(this.$api.usereditcart, {
          product_id: ele.product_id, //商品id
          stock_id: ele.p_s_id,// 规格id
          quantity: ele.quantity,// 数量
        }).then(res => {
          const cart_id = res.data.data
          if (res.data.code == 1) {

            if (list.length - arr.length == 1) {
              arr.push(cart_id)

              this.$store.commit('setcart_id', arr.toString())
              setTimeout(() => {
                this.$router.push({ name: 'settlement' });
              }, 1000);
            } else {
              arr.push(cart_id)
            }
          } else {
            Toast.fail(res.data.msg)
          }

        })
      });

    },
    // 联系客服
    goCustomerService (item) {
      this.$router.push({ name: 'chat', query: { shop_id: item.children[0].shop_id } });
    },
    userafters (id) {
      Dialog.confirm({
        title: "提示",
        message: "确定撤回申请？",
      })
        .then(() => {
          this.$axios
            .post(this.$api.userafters, {
              order_id: id,
            })
            .then(() => {
              Toast.loading({
                message: "取消成功",
                duration: 1000,
              });
              setTimeout(() => {
                this.list = [];
                this.getOrderList(this.tabs_active);
              }, 1000);
            })
            .catch((err) => {
              Toast.fail(err);
            });
        })
        .catch(() => {
          // on cancel
        });
    },

    //展示客服联系方式
    showDialog () {
      Dialog.alert({
        title: "客服联系方式",
        message: "电话：17322733294",
      }).then(() => {
        // on close
      });
    },
    userremind (id) {
      this.$axios
        .post(this.$api.userremind, {
          order_id: id,
        })
        .then(() => {
          Toast.success("已取消售后");
        })
        .catch((err) => {
          Toast.fail(err);
        });
    },

    // 订单详情
    selectOrderDetail (id) {
      this.$router.push({ name: "orderDetail", query: { id: id } });
    },
    // tab改变时
    tabChange (name) {
      this.list = [];
      this.tabs_active = name;
      this.$store.commit("setOrderTab", name);
      this.getOrderList();
      this.finished = false;
    },
    // 搜索
    onSearch () {

      setTimeout(() => {
        this.list = [];
        this.getOrderList();
      }, 500);
    },
    // 获取订单列表
    getOrderList () {
      this.loading = true;
      if (this.loading)
        Toast.loading({ message: "加载中...", forbidClick: true });
      this.$axios
        .get(this.$api.GetOrderList, {
          params: {
            product_name: this.searchValue, //搜索关键字
            status: this.tabs_active == 5 ? 10 : this.tabs_active, //订单状态 1待付款 2待发货 3待收货 4 待评价 5 用户取消订单 6 订单退款 7 订单退货
            is_comment:
              this.tabs_active == 4 ? 2 : null, //订单是否已评价  1已经评价，0没有评价
            page: parseInt(this.list.length / this.limit) + 1, //页码
            limit: this.limit, //每页条数,
            // order_type: this.tabs_active == 5 ? 1 : null,
            order_type: 1,

          },
        })
        .then((res) => {
          if (res.data.code == 1) {

            Toast.clear();
            let result = res.data.data;

            this.list.push(...result.data);

            if (this.tabs_active == 4) {
              this.list = this.list.filter((ele) => {
                return ele.order_type == 1
              })
            }

            this.loading = false;
            if (result.data.length < this.limit) {
              this.finished = true; // 大于所有条数则结束加载
            }
            if (result.length == this.limit) this.page++;

          } else {
            // 加载失败时
            this.err = true;
            this.loading = false;
          }
        });
    },
    // 取消订单
    cancelOrder (id) {
      // this.reson = ''
      // this.show = true
      // this.temp_id = id
      Dialog.confirm({
        title: "提示",
        message: "确定取消订单？",
      })
        .then(() => {
          this.$axios
            .post(this.$api.usercancel, {
              order_id: id,
            })
            .then((res) => {
              if (res.data.code == 1) {
                Toast.loading({
                  message: "取消成功",
                  duration: 1000,
                });
                setTimeout(() => {
                  this.list = [];
                  this.getOrderList(this.tabs_active);
                }, 1000);
              } else {
                Toast.loading({
                  message: res.data.msg,
                  duration: 1000,
                });
              }

            })
            .catch((err) => {
              Toast.fail(err);
            });
        })
        .catch(() => {
          // on cancel
        });
    },
    // 确认取消订单
    onConfirm () {
      // this.$axios.post(this.$api.GetOrderList, {
      //   wytoken: this.$store.state.token,
      //   order_id: this.temp_id,
      //   reson: this.reson //取消原因
      // }).then(() => {
      //   Toast.loading({
      //     message: '取消成功',
      //     duration: 1000,
      //   })
      //   setTimeout(() => {
      //     this.list = []
      //     this.getOrderList(this.tabs_active)
      //   }, 1000);
      // }).catch(err => {
      //   Toast.fail(err)
      // })
    },
    // 查看物流
    // selectLogistics (id) {
    //   console.log(id);
    // },

    // 提醒发货
    remindSend (id) {
      this.$axios
        .post(this.$api.userremind, {
          order_id: id,
        })
        .then(() => {
          Toast.success("已提醒卖家发货");
        })
        .catch((err) => {
          Toast.fail(err);
        });
    },
    // 唤起微信支付
    StartWeiXinPay (pay_params) {
      if (typeof window.WeixinJSBridge === "undefined") {
        if (document.addEventListener) {
          document.addEventListener(
            "WeixinJSBridgeReady",
            this.onBridgeReady(pay_params),
            false
          );
        } else if (document.attachEvent) {
          document.attachEvent(
            "WeixinJSBridgeReady",
            this.onBridgeReady(pay_params)
          );
          document.attachEvent(
            "onWeixinJSBridgeReady",
            this.onBridgeReady(pay_params)
          );
        }
      } else {
        this.onBridgeReady(pay_params);
      }
    },
    onBridgeReady (pay_params) {
      var that = this
      window.WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          appId: pay_params.appId, // 公众号名称，由商户传入
          timeStamp: pay_params.timeStamp, // 时间戳，自1970年以来的秒数
          nonceStr: pay_params.nonceStr, // 随机串
          package: pay_params.package, //统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
          signType: pay_params.signType, // 微信签名方式：
          paySign: pay_params.paySign, // 微信签名
        },
        function (res) {
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
            //  支付成功
            // Toast.success("支付成功");
            // setTimeout(() => {
            //   location.reload();
            // }, 1000);
            setTimeout(() => {
              console.log(that.oid);

              that.$router.replace({ name: 'paymentSucess', query: { order_id: that.oid } })
            }, 500);
          } else {
            // 支付失败
            Toast.fail("支付失败");
            setTimeout(() => {
              location.reload();
            }, 1000);
          }
        }
      );
    },
    // 支付 or 确认收货
    changeOrderState (sign, id) {
      if (sign == 1) {
        // 支付
        this.$axios
          .post(this.$api.tobepaid, {
            order_id: id,
            pay_end: 1,
          })
          .then((res) => {

            if (res.data.code == 1) {
              this.oid = id
              console.log(res.data.data);
              this.StartWeiXinPay(res.data.data.data);
            } else {
              Toast.fail(res.data.msg);
            }
          });

      } else if (sign == 2) {
        // 确认收货
        Dialog.confirm({
          title: "提示",
          message: "该订单确认收货吗？",
          confirmButtonColor: "#FF4133",
        })
          .then(() => {
            this.$axios
              .post(this.$api.usersure, {
                order_id: id,
              })
              .then(() => {
                Toast.success("收货成功");
                this.list = [];
                this.getOrderList(this.tabs_active);
              })
              .catch((err) => {
                Toast.fail(err);
              });
          })
          .catch(() => {
            // on cancel
          });
      }
    },
    refund (item) {

      this.$router.push({
        name: "addaftersale",
        query: {
          id: item.order_id,
          did: item.children[0].detail_id,
        },
      });
    },
    //跳去评论页
    jumpToComment (orderid) {
      this.$router.push({
        name: "addComment",
        query: {
          order_id: orderid,
        },
      });
    },
    //查看物流
    logistics (id) {
      this.$router.push({ name: "logistics", query: { id } });
    },
  },
};
</script>

<style lang="less" scoped>
.changebu {
  background: #f33224;
  color: #fff !important;
  border: 1px solid #ff7733 !important;
}
.btn {
  color: #ff7733 !important;
  border: 1px solid #ff7733 !important;
}
.order {
  position: relative;
  height: 100%;
  box-sizing: border-box;
  .order-search {
    display: flex;
    align-items: center;
    width: 100%;
    height: 70px;
    padding: 16px 8px 0 16px;
    background-color: #fff;
    box-sizing: border-box;
    .arrow-left {
      margin-right: 12px;
    }
    .van-search {
      flex: 1;
      .van-search__content {
        border: 1px solid #f2f2f2;
        border-radius: 6px;
        background-color: #fff;
      }
    }
  }

  /deep/.van-tab__text {
    font-size: 14px;
    font-weight: 400;
    font-weight: bold;
  }
  /deep/.van-tab--active {
    color: #ff7733;
  }
  /deep/.van-tabs__line {
    width: 28px;
    height: 2px;
    background: #ff7733;
  }
  /deep/ .van-tabs__wrap {
    background: white;
    //padding: 4.5px 15px;
    box-sizing: border-box;
  }

  .list {
    .red-special {
      color: @green !important;
    }
    .order-list-panel {
      margin-top: 15px;
      .shopname {
        padding-bottom: 0;
        .van-cell__title {
          flex: 3;
        }
        .van-image {
          width: 21px;
          height: 21px;
          margin-right: 12px;
        }
      }
      .van-card {
        background-color: transparent;
        /deep/ .van-card__title {
          display: block;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        /deep/ .van-card__title,
        /deep/ .van-card__price {
          color: #1d1d1d;
          font-size: 14px;
        }
        /deep/ .van-card__desc {
          color: #827f7f;
          margin-top: 5px;
        }
      }
      .pay_amount {
        .van-cell__value {
          color: #000;
          font-size: 14px;
        }
        .price {
          font-weight: bold;
        }
        .name {
          font-weight: 400;
        }
      }
      .express_fee {
        font-size: 12px;
        color: rgba(25, 23, 20, 0.3);
        margin-right: 5px;
      }
      .list-item-options {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        width: 100%;
        padding: 0 10px 10px;
        box-sizing: border-box;
        .van-button {
          width: 100px;
          margin: 0 6px;
          border: 1px solid rgba(6, 2, 26, 0.3);
        }
        /deep/.van-button__text {
          font-size: 14px;
        }
      }
    }
  }
}
/deep/ .van-tab {
  padding: 0 1.3vw;
}
</style>